<?php
/**
 * Dons
 *
 * Description de la classe
 *
 * @author Valentin
 */
class Don extends Object {
    protected $id;
    protected $association_id;
    protected $transaction_id;
    protected $user_id;
    protected $montant;
    protected $anonyme;
    protected $state;
    protected $added;
    protected $don;
    protected $newsletter;

    protected $association;

    function __construct($id="", $params=array()) {
        if($id!='') {
            $this->id = $id;
            foreach($params as $key => $p) {
                $this->$key = $p;
            }
        }
    }

    function __toString() {
        return $this->montant;
    }

    public function load() {
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM dons WHERE id = '".$this->id."'");
        if(sizeof($result) > 0) {
            foreach($result[0] as $key => $p) {
                $this->$key = $p;
            }
            return;
        }
        if(DEBUG) echo("Objet inconnu");
        return false;
    }

    public function save(){
        $db = Database::getInstance();
        if(isset($this->id)){
            $sql="UPDATE dons SET state='".$this->state."' WHERE id = '".$this->id."'";
            $db->query($sql);
        }
        else{
         $sql="INSERT INTO dons (association_id, transaction_id, user_id, state, montant) VALUES ('".$this->association_id."','".$this->transaction_id."','".$this->user_id."','".$this->state."', '".$this->montant."')";
         $db->query($sql);
         $this->id= $db->getInsertedId();
        }
    }

    public function getAssociation() {
        if(isset($this->association)) return $this->association;
        if(!isset($this->association_id)) $this->load();
        $this->association = new Association($this->association_id);
        return $this->association;
    }

    static function getSumDons() {
        $db = Database::getInstance();
        $result = $db->query("SELECT SUM(montant) from dons WHERE state='0'");
        return (string)floor($result[0]['SUM(montant)']);
    }
    static function get($transaction){
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM dons WHERE transaction_id='".$transaction['id']."'");
        if(sizeof($result) > 0) {
            $donations=array();
            foreach($result as $line){
                $donations[]=new Don($line['id'],$line);
            }
            return $donations;
        }
        return false;
    }
}
?>
